﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using DocumentManagement.Models;

namespace DocumentManagement.Controllers
{

    [HandleError]
    public class AccountController : BaseController
    {
        [Authentication( PermissionLevel.AccountNormal)]
        public ActionResult Index()
        {
            return this.View("index");
        }

        public ActionResult ShowLogin()
        {
            if (this.AuthenticatedUser == null)
            {
                return View("login");
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [AcceptVerbs( HttpVerbs.Post)]
        public ActionResult AuthenticateUser(int uid, string pwd)
        {
            var user = this.Model.AuthenticateUser(uid, pwd);
            this.HttpContext.Session[Consts.UidSessionKey] = uid;

            return RedirectToAction("Index", "Home");
        }

        [AcceptVerbs( HttpVerbs.Post)]
        [Authentication(PermissionLevel.AccountNormal)]
        public ActionResult ChangePassword(string oldPwd, string newPwd, string newPwd2)
        {
            if (newPwd != newPwd2 || string.IsNullOrEmpty(newPwd))
            {
                throw new InvalidOperationException("错误的密码");
            }

            this.Model.ChangePassword(this.AuthenticatedUser.id, oldPwd, newPwd);

            return RedirectToAction("Index", "Home");
        }

        [Authentication(PermissionLevel.AccountNormal)]
        public ActionResult ShowChangePassword()
        {
            return View("ChangePassword");
        }
    }
}
